package com.sywb.chuangyebao.view;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Comment;
import com.sywb.chuangyebao.contract.VideoDetailContract;
import com.sywb.chuangyebao.library.player.AliPlayerView;
import com.sywb.chuangyebao.library.player.IVideoController;
import com.sywb.chuangyebao.library.player.listener.OnPlayerListener;
import com.sywb.chuangyebao.utils.RegexUtils;
import com.sywb.chuangyebao.utils.ScreenSwitchUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.dialog.CommentReplyDialog;

import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.utils.SoftKeyboardUtils;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.widget.PullToRefreshView;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 视频新闻
 */
public class VideoDetailActivity extends SupportCommentDetailActivity<VideoDetailContract.Presenter> implements VideoDetailContract.View {

    @BindView(R.id.ll_container)
    FrameLayout llContainer;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_operation)
    ImageView ivOperation;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.common_nodata_content)
    TextView commonNodataContent;
    @BindView(R.id.common_nodata_icon)
    ImageView commonNodataIcon;
    @BindView(R.id.common_nodata_subtitle)
    TextView commonNodataSubtitle;
    @BindView(R.id.common_nodata)
    RelativeLayout commonNodata;
    @BindView(R.id.common_recycler_layout)
    RelativeLayout commonRecyclerLayout;
    @BindView(R.id.full_screen)
    FrameLayout fullScreen;

    @BindView(R.id.ll_showinfo)
    LinearLayout llShowInfo;
    @BindView(R.id.tv_content)
    TextView tvContent;

    @BindView(R.id.iv_comment)
    ImageView ivComment;
    @BindView(R.id.tv_comment_count)
    TextView tvCommentCount;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    @BindView(R.id.iv_share)
    ImageView ivShare;

    @BindView(R.id.ll_write_comment)
    LinearLayout llWriteComment;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_send)
    TextView tvSend;

    @BindView(R.id.tv_consult)
    TextView tvConsult;

    private ScreenSwitchUtils instance;

    private AliPlayerView videoPlayer;

    private boolean orientation = false;//默认为竖屏的情况

    private int videoId;
    private int postion;
    private long currentPosition;

    private Comment mComment; // 如果有此参数，表示从个人中心我的评论进入，当加载完文章后需要自动弹出CommentReplyDialog

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_video_detail;
    }

    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        instance = ScreenSwitchUtils.init(this.getApplicationContext());

        if (bundle == null) {
            bundle = getIntent().getExtras() == null ? new Bundle() : getIntent().getExtras();
        }

        videoId = bundle.getInt("p0", 0);
        postion = bundle.getInt("p1", 0);
        currentPosition = bundle.getLong("p2", 0L);
        mComment = (Comment) bundle.getSerializable("p3");

        videoPlayer = new AliPlayerView(mContext);
        videoPlayer.setOnPlayerListener(new OnPlayerListener() {
            @Override
            public void onInit() {
                ivBack.setVisibility(View.VISIBLE);
                ivOperation.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPrepared() {
                ivBack.setVisibility(View.GONE);
                ivOperation.setVisibility(View.GONE);
            }

            @Override
            public void onStarted() {
                ivBack.setVisibility(View.GONE);
                ivOperation.setVisibility(View.GONE);
                instance.start(mActivity);

                if (currentPosition > 0) {
                    videoPlayer.seekTo((int) currentPosition);
                    currentPosition = 0L;
                }
            }

            @Override
            public void onPaused() {
                ivBack.setVisibility(View.VISIBLE);
                ivOperation.setVisibility(View.VISIBLE);
                instance.stop();
            }

            @Override
            public void onCompletion() {
                ivBack.setVisibility(View.VISIBLE);
                ivOperation.setVisibility(View.VISIBLE);
                instance.stop();
            }

            @Override
            public void onError(int causeCode, int sceneCode, String message) {
                ivBack.setVisibility(View.VISIBLE);
                ivOperation.setVisibility(View.VISIBLE);
                instance.stop();
            }

            @Override
            public void onShare(int platformType) {
                mPresenter.showDialog();
            }

            @Override
            public void onClickScreenDirection() {
                instance.toggleScreen();
            }

            @Override
            public void showToolsView() {
                ivBack.setVisibility(View.VISIBLE);
                ivOperation.setVisibility(View.VISIBLE);
            }

            @Override
            public void hideToolsView() {
                ivBack.setVisibility(View.GONE);
                ivOperation.setVisibility(View.GONE);
            }

            @Override
            public void updateProgress(int curPosition, int bufferPosition, int duration) {
            }

        });

        llContainer.addView(videoPlayer);
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", videoId);
        outState.putInt("p1", postion);
        outState.putLong("p2", currentPosition);
        outState.putSerializable("p3", mComment);
        super.onSaveInstanceState(outState);
    }

    @OnClick({R.id.iv_operation, R.id.tv_content, R.id.iv_comment, R.id.tv_comment_count, R.id.iv_collect, R.id.iv_share, R.id.tv_send, R.id.tv_consult})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_operation:
                mPresenter.showDialog();
                break;
            case R.id.tv_content:
                if (!Utils.checkIsNext(getMyFragmentManager())) {
                    return;
                }

                llWriteComment.setVisibility(View.VISIBLE);
                llShowInfo.setVisibility(View.GONE);

                etContent.setFocusable(true);
                etContent.setFocusableInTouchMode(true);
                etContent.requestFocus();
                etContent.requestFocusFromTouch();

                SoftKeyboardUtils.openSoftKeybord(etContent);
                break;
            case R.id.iv_comment:
            case R.id.tv_comment_count:
                mPresenter.goViewTop();
                break;
            case R.id.iv_collect:
                mPresenter.favorite();
                break;
            case R.id.iv_share:
                mPresenter.showDialog();
                break;
            case R.id.tv_send:
                String content = etContent.getText().toString();
                if (content.isEmpty()) {
                    ToastUtils.show(mContext, "请输入评论内容");
                } else {
                    mPresenter.addComment(content);
                    etContent.setText("");
                    SoftKeyboardUtils.stopSoftKeybord(etContent);
                    llShowInfo.setVisibility(View.VISIBLE);
                    llWriteComment.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_consult:
                if (mPresenter != null) {
                    mPresenter.goConsult();
                }
                break;
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(ConnectivityManager.CONNECTIVITY_ACTION)})
    public void netwotkChange(String data) {
        Logger.e("netwotkChange:" + data);
        videoPlayer.inspectPlayer();
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.HTTP_COMMENTREPLY_ADD)})
    public void commentCount(String data) {
        Logger.e("commentCount:" + data);
        String[] datas = data.split("&");
        mPresenter.changeCommentCount(Integer.valueOf(datas[1]), Integer.valueOf(datas[2]));
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.POST_THUMB)})
    public void commentThumb(String data) {
        Logger.e("commentThumb:" + data);
        String[] datas = data.split("&");
        mPresenter.changeCommentThumb(Integer.valueOf(datas[1]), Boolean.valueOf(datas[2]), Integer.valueOf(datas[3]));
    }

    public int getPageNum() {
        return 4;
    }

    public int getProjectId() {
        return 0;
    }

    public int getNewsId() {
        return 0;
    }

    @Override
    public boolean useRxBus() {
        return true;
    }

    /**
     * 横竖屏切换
     *
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        boolean orientation = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;
        videoPlayer.onConfigurationChanged(newConfig);
        onConfigurationChanged(orientation);
    }

    public void onConfigurationChanged(boolean screenDirection) {
        if (!screenDirection) {// 竖屏
            Logger.e("竖屏");
            orientation = false;
            fullScreen.setVisibility(View.GONE);
            fullScreen.removeAllViews();
            llContainer.removeAllViews();
            llContainer.addView(videoPlayer);
            int mShowFlags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            fullScreen.setSystemUiVisibility(mShowFlags);
        } else { // 横屏
            Logger.e("横屏");
            orientation = true;
            ViewGroup viewGroup = (ViewGroup) videoPlayer.getParent();
            if (viewGroup == null) {
                return;
            }
            viewGroup.removeAllViews();
            fullScreen.addView(videoPlayer);
            fullScreen.setVisibility(View.VISIBLE);
            int mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            fullScreen.setSystemUiVisibility(mHideFlags);
        }
    }

    /**
     * 返回键的处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 横屏播放的情况
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return true;
            } else {
                exit();
            }
        }
        return false;
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        if (orientation) {
            videoPlayer.changedConfiguration();
        } else {
            exit();
        }
    }

    @Override
    protected void onResume() {
        videoPlayer.autoResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        videoPlayer.autoPause();
        instance.stop();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        videoPlayer.destroy();
        super.onDestroy();
    }

    @Override
    public void exit() {
        Intent intent = new Intent();
        intent.putExtra("p0", videoId);
        intent.putExtra("p1", postion);
        intent.putExtra("p2", videoPlayer.getAliyunVodPlayer().getCurrentPosition());
        setResult(RESULT_OK, intent);
        exit(false);
    }

    @Override
    public RecyclerView getRecyclerView() {
        return rvComment;
    }

    @Override
    public void setNoData(boolean isNoData) {
    }

    @Override
    public int getDialogViewHeight() {
        return content.getHeight() - videoPlayer.getHeight();
    }

    @Override
    public void changeCommentCount(int count) {
        if (count > 0) {
            tvCommentCount.setText(RegexUtils.getFormatNum(count));
            tvCommentCount.setVisibility(View.VISIBLE);
        } else {
            tvCommentCount.setVisibility(View.GONE);
        }
    }

    @Override
    public void setIsFavorite(boolean isFavorite) {
        if (isFavorite) {
            ivCollect.setImageResource(R.drawable.collect_bb_fill);
        } else {
            ivCollect.setImageResource(R.drawable.collect_bb);
        }
    }

    @Override
    public int getVideoId() {
        return videoId;
    }

    @Override
    public void startPlay(String videoUrl, String previewPath) {
        videoPlayer.init(mActivity, IVideoController.MODE_VIDEO, videoUrl, previewPath, "00:00");
        videoPlayer.start();
    }

    @Override
    public PullToRefreshView getPullToRefreshView() {
        return null;
    }

    @Override
    public Comment getComment() {
        return mComment;
    }

    @Override
    public void setConsultState(boolean isConsult) {
        tvConsult.setVisibility(isConsult ? View.VISIBLE : View.GONE);
    }
}
